<template>
  <div>
    <el-dialog
      class="custom-dialog"
      v-model="dialogVisible"
      align-center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="视频回放"
      width="1200px"
      @close="handleClose"
    >
      <div class="detail">
        <div class="info">
          <el-row :gutter="20">
            <el-col :span="12">
              <span class="label">设备名称:</span>
              <span class="value">{{ detail.nickName }}</span>
            </el-col>
            <el-col :span="12">
              <span class="label">设备位置:</span>
              <span class="value"
                >{{ detail.address }}
                <svg-icon name="location" @click="handleLocation" />
              </span>
            </el-col>
          </el-row>
        </div>

        <div class="dialog-content">
          <div class="left">
            <div class="date">
              <el-date-picker
                v-model="date"
                :clearable="false"
                type="month"
                value-format="YYYY-MM"
                placeholder="请选择月份"
              />
            </div>

            <div id="playback-video" class="video-wrapper">
              <img v-if="url" style="width: 100%; height: 100%" :src="azImg2" />
              <div class="video-no" v-else>
                <div class="img" />
                <span>请先选择时间段</span>
              </div>
            </div>
          </div>

          <div class="right">
            <el-skeleton v-if="!date" />

            <el-calendar
              v-loading="dateLoading"
              v-if="date"
              v-model="calendarDate"
            >
              <template #date-cell="{ data }">
                <el-badge
                  :is-dot="
                    videoDateList.find(
                      (item) =>
                        item.dayOfMonth.toString() ===
                        data.day.split('-').at(-1),
                    )?.record &&
                    dayjs(data.day).format('MM') ===
                      dayjs(calendarDate).format('MM')
                  "
                  type="primary"
                >
                  <span>{{ data.day.split('-').at(-1) }}</span>
                </el-badge>
              </template>
            </el-calendar>

            <el-button
              v-if="date"
              :disabled="searchButtonDisabled"
              type="primary"
              @click="handleSearchTimeRange"
            >
              查找
            </el-button>

            <div v-if="date && timeRangeList.length" class="time-range-wrapper">
              <el-scrollbar>
                <div
                  v-for="(item, index) in timeRangeList"
                  :key="index"
                  :class="[
                    'time-range-item',
                    index === selectedTimeRangeIndex ? 'active' : '',
                  ]"
                  @click="handleTimeRangeSelect(index)"
                >
                  <span
                    >{{
                      item.timeSpan.startTime.replace('T', ' ').replace('Z', '')
                    }}
                    ~
                    {{
                      item.timeSpan.endTime.replace('T', ' ').replace('Z', '')
                    }}</span
                  >
                </div>
              </el-scrollbar>

              <el-button
                :disabled="playButtonDisabled"
                type="primary"
                @click="handlePlay"
              >
                播放
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    <ChooseLocation
      v-model:dialog-visible="chooseLocationDialogVisible"
      :disabled="true"
      :latlnt="detail.position"
      :device-location="detail.nickName"
    />
  </div>
</template>
<script setup>
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { computed, ref, watch } from 'vue'
import Player from 'xgplayer'
import HlsPlugin from 'xgplayer-hls'

import azImg2 from '@/assets/imgs/manager/azImg2.png'
import {
  queryVideoDate,
  queryVideoPlaybackStream,
  queryVideoTimeRange,
} from '@/api/manager/dataManage/deviceManage'
import ChooseLocation from '@/components/chooseLocation.vue'

let player = null

const props = defineProps({
  detail: {
    type: Object,
    default: () => {},
  },
})

const emit = defineEmits(['close'])

const dialogVisible = ref(false)

const url = ref('')

const date = ref('')

const calendarDate = ref('')

const chooseLocationDialogVisible = ref(false)

const dateLoading = ref(false)

const videoDateList = ref([])

const timeRangeList = ref([])

const selectedTimeRangeIndex = ref(-1)

const handleLocation = () => {
  if (props.detail.position) {
    const lngLat = props.detail.position.split(',')
    if (
      lngLat.filter(
        (item) => item !== undefined && item !== '' && item.trim() !== '',
      ).length === 2
    ) {
      chooseLocationDialogVisible.value = true
    } else {
      ElMessage.error('位置数据错误')
    }
  } else {
    ElMessage.error('无位置数据')
  }
}

/**
 * 搜索某一天有记录的时间范围
 */
const handleSearchTimeRange = () => {
  timeRangeList.value = []
  selectedTimeRangeIndex.value = -1
  queryVideoTimeRange({
    pkid: props.detail.pkid,
    startTime: dayjs(calendarDate.value).format('YYYY-MM-DD') + ' 00:00:00',
    endTime: dayjs(calendarDate.value).format('YYYY-MM-DD') + ' 23:59:59',
  }).then((res) => {
    if (res.success) {
      timeRangeList.value = res.data.CMSearchResult.matchList.searchMatchItem
    } else {
      ElMessage.error(res.message || '查询时间范围失败')
    }
  })
}

/**
 * 选择时间范围
 */
const handleTimeRangeSelect = (index) => {
  selectedTimeRangeIndex.value = index
}

const handlePlay = () => {
  queryVideoPlaybackStream({
    pkid: props.detail.pkid,
    startTime: timeRangeList.value
      .at(selectedTimeRangeIndex.value)
      .timeSpan.startTime.replace('T', ' ')
      .replace('Z', ''),
  }).then((res) => {
    if (res.success) {
      console.log('播放地址', res)
      url.value = `${window.VIDEO_BASE_URL}/hls/${res.data}/hls.m3u8`
      if (!player) {
        initPlayer()
      } else {
        // player.switchURL(url.value)
        try {
          player.destroy()
        } catch (error) {
          console.error('player destroy failed:', error)
        }
        player = null
        initPlayer()
      }
    } else {
      ElMessage.error(res.message || '获取播放地址失败')
    }
  })
}

const initPlayer = () => {
  player = new Player({
    id: 'playback-video',
    url: url.value,
    width: '100%',
    height: '420px',
    autoplay: true,
    autoplayMuted: true,
    fitVideoSize: 'fixed',
    videoFillMode: 'contain',
    isLive: false,
    plugins: [HlsPlugin],
  })
  player.on('loadstart', () => {
    console.log('player loadstart')
  })
  player.on('loadeddata', () => {
    console.log('player loadeddata')
  })
  player.on('error', (error) => {
    console.warn('player error', error)
  })
}

const handleClose = () => {
  dialogVisible.value = false
  date.value = ''
  calendarDate.value = ''
  videoDateList.value = []
  timeRangeList.value = []
  selectedTimeRangeIndex.value = -1
  url.value = ''
  if (player) {
    try {
      player.destroy()
    } catch (error) {
      console.error('player destroy failed:', error)
    }
    player = null
  }
  dateLoading.value = false
  emit('close')
}

const searchButtonDisabled = computed(
  () =>
    // 未选择具体日期或者该日期没有记录时禁止点击查找按钮
    dayjs(calendarDate.value, 'YYYY-MM', true).isValid() ||
    !videoDateList.value.find(
      (item) =>
        item.dayOfMonth.toString() === dayjs(calendarDate.value).format('DD'),
    )?.record,
)

const playButtonDisabled = computed(
  () =>
    !timeRangeList.value.length ||
    selectedTimeRangeIndex.value === -1 ||
    !timeRangeList.value.at(selectedTimeRangeIndex.value),
)

watch(
  () => date.value,
  (val) => {
    videoDateList.value = []
    timeRangeList.value = []
    selectedTimeRangeIndex.value = -1
    url.value = ''
    if (props.detail.pkid) {
      const yearMonth = val.split('-')
      calendarDate.value = date.value
      dateLoading.value = true
      queryVideoDate({
        pkid: props.detail.pkid,
        year: yearMonth[0],
        month: yearMonth[1],
      })
        .then((res) => {
          if (res.success) {
            videoDateList.value =
              res.data.trackDailyDistribution.dayList.day || []
          } else {
            ElMessage.error(res.message || '查询录像失败')
          }
        })
        .finally(() => {
          dateLoading.value = false
        })
    }
  },
)

watch(
  () => calendarDate.value,
  (val) => {
    date.value = dayjs(val).format('YYYY-MM')
  },
)

defineExpose({ dialogVisible })
</script>
<style lang="scss" scoped>
.detail {
  width: 100%;
  display: flex;
  flex-direction: column;
  .info {
    width: 100%;
    height: 36px;
    background: rgba(117, 117, 117, 0.05);
    border-radius: 4px;
    margin-bottom: 20px;
    :deep(.el-row) {
      height: 100%;
      display: flex;
      align-items: center;
    }
    .label {
      font-size: 14px;
      line-height: 16px;
      font-weight: 400;
      color: #333333;
      display: inline-block;
      margin-right: 10px;
      text-align: right;
      width: 80px;
    }
    .value {
      display: inline-block;
      font-size: 14px;
      line-height: 16px;
      font-weight: 400;
      color: #757575;
      .svg-icon {
        width: 15px;
        height: 14px;
        margin: 0px 0 0 10px;
        cursor: pointer;
      }
    }
  }

  .dialog-content {
    display: flex;

    .left {
      width: 70%;
      display: flex;
      flex-direction: column;
    }

    .right {
      flex: 1;
      max-height: 472px;
      margin-left: 20px;
      display: flex;
      flex-direction: column;
      align-items: center;
      overflow: hidden;

      .el-calendar {
        --el-calendar-cell-width: 40px;

        :deep(.el-calendar__header) {
          display: none;
        }

        :deep(.el-calendar__body) {
          padding: 0 0 10px;
        }

        :deep(.el-calendar-day) {
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }

      .el-button {
        width: fit-content;
      }

      .time-range-wrapper {
        width: 100%;
        flex: 1;
        margin-top: 10px;
        display: flex;
        flex-direction: column;
        align-items: center;
        overflow: hidden;

        .el-scrollbar {
          width: 100%;
          flex: 1;
        }

        .time-range-item {
          width: 100%;
          padding: 6px 10px;
          border-radius: 2px;
          border: 1px solid var(--el-border-color);
          background-color: '#ffffff';
          cursor: pointer;
          transition: all 0.3s ease-in-out;

          &:not(:first-of-type) {
            margin-top: 10px;
          }

          &.active {
            border-color: var(--el-color-primary);
            background-color: var(--el-border-color);
          }
        }

        .el-button {
          margin-top: 10px;
        }
      }
    }
  }

  .date {
    width: 100%;
    margin-bottom: 20px;
  }

  .video-wrapper {
    width: 100%;
    height: 420px;
    .video-no {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      .img {
        width: 450px;
        height: 280px;
        background: url('@/assets/imgs/manager/no-video.png') no-repeat;
        background-size: 100% 100%;
      }
      span {
        position: absolute;
        top: 280px;
        font-size: 14px;
        font-weight: 400;
        color: #757575;
      }
    }
  }
}
</style>
